



import * as dotenv from "dotenv";


dotenv.config();

import { characterDetails, responseTypes, questionKeywords, relationshipKeywords, eventsDetails } from './characterData.js';

// 关键词匹配函数 - 找出用户问题中提到的人物
function findMentionedCharacters(userMessage) {
  const mentionedCharacters = [];
  const messageLower = userMessage.toLowerCase();

  // 检查是否提到了任何三国人物
  for (const [key, character] of Object.entries(characterDetails)) {
    // 检查人物姓名
    if (messageLower.includes(character.name.toLowerCase())) {
      mentionedCharacters.push({
        key,
        name: character.name,
        detail: character,
        type: 'name'
      });
      continue;
    }

    // 检查人物别名
    if (character.alias) {
      for (const alias of character.alias) {
        if (messageLower.includes(alias.toLowerCase())) {
          mentionedCharacters.push({
            key,
            name: character.name,
            detail: character,
            type: 'alias'
          });
          break;
        }
      }
    }
  }

  return mentionedCharacters;
}

// 关键词匹配函数 - 找出用户问题中提到的事件
function findMentionedEvents(userMessage) {
  const mentionedEvents = [];
  const messageLower = userMessage.toLowerCase();

  for (const [key, event] of Object.entries(eventsDetails)) {
    if (messageLower.includes(key.toLowerCase())) {
      mentionedEvents.push({
        key,
        detail: event
      });
    }
  }

  return mentionedEvents;
}

// 分析问题类型
function analyzeQuestionType(userMessage) {
  let questionType = 'general';
  let maxScore = 0;
  const messageLower = userMessage.toLowerCase();

  // 为每个问题类型计算匹配分数
  for (const [type, keywords] of Object.entries(questionKeywords)) {
    const score = keywords.filter(keyword => messageLower.includes(keyword)).length;
    if (score > maxScore) {
      maxScore = score;
      questionType = type;
    }
  }

  return questionType;
}

// 生成关于人物的回复
function generateCharacterResponse(characterKey, characterDetail, questionType, userMessage) {
  const messageLower = userMessage.toLowerCase();

  // 根据问题类型生成不同类型的回复
  switch (questionType) {
    case 'personality':
      return generatePersonalityResponse(characterDetail);
    case 'achievements':
      return generateAchievementsResponse(characterDetail);
    case 'quotes':
      return generateQuotesResponse(characterDetail);
    case 'subordinates':
      return generateSubordinatesResponse(characterDetail);
    case 'events':
      return generateEventsResponse(characterDetail);
    case 'introduction':
      return generateIntroductionResponse(characterDetail);
    default:
      return generateGeneralCharacterResponse(characterDetail);
  }
}

// 生成人物性格回复
function generatePersonalityResponse(characterDetail) {
  const prefix = responseTypes.personal[Math.floor(Math.random() * responseTypes.personal.length)];
  return `${prefix}${characterDetail.name}为人${characterDetail.personality}，是三国时期难得的${characterDetail.role.includes('名将') ? '猛将' : '英雄人物'}。`;
}

// 生成人物成就回复
function generateAchievementsResponse(characterDetail) {
  const prefix = responseTypes.historical[Math.floor(Math.random() * responseTypes.historical.length)];

  if (characterDetail.achievements && characterDetail.achievements.length > 0) {
    // 随机选择2-3个成就
    const selectedAchievements = [];
    const count = Math.min(3, Math.max(2, characterDetail.achievements.length));

    for (let i = 0; i < count && selectedAchievements.length < characterDetail.achievements.length; i++) {
      let randomIndex;
      do {
        randomIndex = Math.floor(Math.random() * characterDetail.achievements.length);
      } while (selectedAchievements.includes(characterDetail.achievements[randomIndex]));

      selectedAchievements.push(characterDetail.achievements[randomIndex]);
    }

    return `${prefix}${characterDetail.name}一生 ${selectedAchievements.join('，')}，立下了赫赫战功。`;
  }

  return `${prefix}${characterDetail.name}一生征战无数，为${characterDetail.role.includes('蜀汉') ? '蜀汉' : characterDetail.role.includes('曹魏') ? '曹魏' : '孙吴'}政权的建立和巩固做出了重要贡献。`;
}

// 生成人物名言回复
function generateQuotesResponse(characterDetail) {
  const prefix = responseTypes.praise[Math.floor(Math.random() * responseTypes.praise.length)];

  if (characterDetail.famousQuotes && characterDetail.famousQuotes.length > 0) {
    const randomQuote = characterDetail.famousQuotes[Math.floor(Math.random() * characterDetail.famousQuotes.length)];
    return `${prefix}${characterDetail.name}曾说过："${randomQuote}"`;
  }

  return `${prefix}${characterDetail.name}虽未留下太多传世名言，但其言行举止却为后人所称道。`;
}

// 生成人物部下回复
function generateSubordinatesResponse(characterDetail) {
  const prefix = responseTypes.introduction[Math.floor(Math.random() * responseTypes.introduction.length)];

  if (characterDetail.subordinates && characterDetail.subordinates.length > 0) {
    // 随机选择3-5个部下
    const selectedSubordinates = [];
    const count = Math.min(5, Math.max(3, characterDetail.subordinates.length));

    for (let i = 0; i < count && selectedSubordinates.length < characterDetail.subordinates.length; i++) {
      let randomIndex;
      do {
        randomIndex = Math.floor(Math.random() * characterDetail.subordinates.length);
      } while (selectedSubordinates.includes(characterDetail.subordinates[randomIndex]));

      selectedSubordinates.push(characterDetail.subordinates[randomIndex]);
    }

    const subordinatesStr = selectedSubordinates.join('、');
    return `${prefix}${characterDetail.name}手下有许多杰出的将领和谋臣，如${subordinatesStr}等，这些人都是辅佐其成就大业的重要力量。`;
  }

  return `${prefix}${characterDetail.name}手下人才济济，聚集了许多能征善战的将领和足智多谋的谋士。`;
}

// 生成人物经历回复
function generateEventsResponse(characterDetail) {
  const prefix = responseTypes.narrative[Math.floor(Math.random() * responseTypes.narrative.length)];

  if (characterDetail.keyEvents && characterDetail.keyEvents.length > 0) {
    // 随机选择2-3个关键事件
    const selectedEvents = [];
    const count = Math.min(3, Math.max(2, characterDetail.keyEvents.length));

    for (let i = 0; i < count && selectedEvents.length < characterDetail.keyEvents.length; i++) {
      let randomIndex;
      do {
        randomIndex = Math.floor(Math.random() * characterDetail.keyEvents.length);
      } while (selectedEvents.includes(characterDetail.keyEvents[randomIndex]));

      selectedEvents.push(characterDetail.keyEvents[randomIndex]);
    }

    const eventsStr = selectedEvents.join('、');
    return `${prefix}${characterDetail.name}一生经历了许多重要事件，如${eventsStr}等，这些事件见证了其从平凡到伟大的历程。`;
  }

  return `${prefix}${characterDetail.name}一生波澜壮阔，经历了无数次战役和政治斗争，最终成为${characterDetail.role}。`;
}

// 生成人物介绍回复
function generateIntroductionResponse(characterDetail) {
  const prefix = responseTypes.introduction[Math.floor(Math.random() * responseTypes.introduction.length)];

  let response = `${prefix}${characterDetail.name}，字${characterDetail.alias ? characterDetail.alias.find(a => a.includes('字'))?.replace('字', '') || '未知' : '未知'}，${characterDetail.origin}人，生活在${characterDetail.period}。`;

  if (characterDetail.background) {
    response += ` ${characterDetail.background}。`;
  }

  if (characterDetail.role) {
    response += ` 最终成为${characterDetail.role}。`;
  }

  return response;
}

// 生成一般人物回复
function generateGeneralCharacterResponse(characterDetail) {
  const prefix = responseTypes.personal[Math.floor(Math.random() * responseTypes.personal.length)];
  let response = '';

  // 随机选择回复类型
  const responseTypes = ['introduction', 'personality', 'achievement', 'quote'];
  const randomType = responseTypes[Math.floor(Math.random() * responseTypes.length)];

  switch (randomType) {
    case 'introduction':
      response = generateIntroductionResponse(characterDetail);
      break;
    case 'personality':
      response = generatePersonalityResponse(characterDetail);
      break;
    case 'achievement':
      response = generateAchievementsResponse(characterDetail);
      break;
    case 'quote':
      response = generateQuotesResponse(characterDetail);
      break;
  }

  return response;
}

// 生成关于事件的回复
function generateEventResponse(eventDetail) {
  const prefix = responseTypes.historical[Math.floor(Math.random() * responseTypes.historical.length)];

  let response = `${prefix}${eventDetail.time}，${eventDetail.participants.join('与')}之间爆发了著名的${eventDetail.key}。`;

  if (eventDetail.commanders) {
    response += ` 此战中，${eventDetail.commanders.join('担任')}联军统帅。`;
  }

  response += ` 最终${eventDetail.result}。`;

  if (eventDetail.significance) {
    response += ` 这场战役${eventDetail.significance}。`;
  }

  return response;
}

// 生成通用回复
function generateGeneralResponse(currentCharacterKey) {
  const currentCharacter = characterDetails[currentCharacterKey];

  // 根据当前角色生成不同的通用回复
  const responses = {
    liuBei: [
      '备当以仁义为本，以礼待人，愿闻先生高见。',
      '夫济大事必以人为本，今人归吾，吾何忍弃去！',
      '汉室倾颓，奸臣窃命，备不量力，欲伸大义于天下。',
      '孤之有孔明，犹鱼之有水也。',
      '勿以恶小而为之，勿以善小而不为。'
    ],
    caoCao: [
      '夫英雄者，胸怀大志，腹有良谋，将军可有此等抱负？',
      '老骥伏枥，志在千里；烈士暮年，壮心不已。',
      '何以解忧？唯有杜康。',
      '对酒当歌，人生几何！譬如朝露，去日苦多。',
      '设使国家无有孤，不知当几人称帝，几人称王。'
    ],
    sunQuan: [
      '能用众力，则无敌于天下矣，孤当与江东父老共图大事。',
      '士别三日，即更刮目相待。',
      '孤承父兄余业，思有桓文之功。',
      '夫存不忘亡，安必虑危，古之善教。',
      '孤与老贼，势不两立。'
    ]
  };

  // 如果当前角色没有预定义回复，则使用通用回复
  const characterResponses = responses[currentCharacterKey] || [
    '某以为此事尚需从长计议，将军以为如何？',
    '古人云："知己知彼，百战不殆"，不知将军有何见解？',
    '天下大势，分久必合，合久必分，此乃天道也。',
    '大丈夫生于乱世，当带三尺剑立不世之功！',
    '胜负乃兵家常事，将军不必介怀。'
  ];

  return characterResponses[Math.floor(Math.random() * characterResponses.length)];
}

// 增强的关键词匹配AI回复生成函数
function generateKeywordBasedResponse(currentCharacterKey, userMessage) {
  try {
    // 安全检查
    if (!currentCharacterKey || !userMessage) {
      return '请明确您的问题。';
    }

    // 转换为小写以便匹配
    const questionLower = userMessage.toLowerCase();

    // 问候语检测和特殊回复
    if (questionLower.includes('你好') || questionLower.includes('您好') || questionLower.includes('久仰') || questionLower.includes('幸会')) {
      const greetings = {
        liuBei: '久仰久仰，不知壮士有何指教？',
        caoCao: '哈哈，先生来得正好，孤正想找人聊聊天下大势。',
        sunQuan: '幸会幸会，不知将军有何见教？'
      };
      return greetings[currentCharacterKey] || '幸会，请问有何指教？';
    }

    // 检查是否提到了其他三国人物
    const mentionedCharacters = findMentionedCharacters(userMessage);

    // 检查是否提到了历史事件
    const mentionedEvents = findMentionedEvents(userMessage);

    // 分析问题类型
    const questionType = analyzeQuestionType(userMessage);

    // 生成回复
    let response = '';

    // 增强关键词匹配 - 先检查常见问题
    if (!response) {
      // 角色特定的关键词响应
      const characterSpecificResponses = {
        liuBei: {
          '长坂坡': '长坂坡之战，某被曹军追击，弃妻离子，幸得子龙单骑救主，翼德据水断桥，方得脱险。此乃某生平至险之时也。',
          '赤壁之战': '赤壁之战，某与孙权联手，以火攻之计大破曹军八十万。公瑾与孔明之功不可没也。',
          '三顾茅庐': '某为请诸葛亮出山，曾三次前往隆中拜访。先生感某诚意，提出《隆中对》，为某规划了三分天下的战略。',
          '五虎上将': '某手下有五虎上将，分别是关羽、张飞、赵云、马超、黄忠。此五人皆万人敌也，为某立下汗马功劳。',
          '诸葛亮': '诸葛亮字孔明，某之军师也。足智多谋，鞠躬尽瘁，死而后已。某得孔明，如鱼得水。'
        },
        caoCao: {
          '长坂坡': '长坂坡之战，某率大军南下追击刘备。刘备军大败，但赵云单骑救主，保护幼主刘禅脱险。张飞据水断桥，喝退吾军，真乃猛将也。',
          '赤壁之战': '赤壁之战，某被孙刘联军火攻所败，折损大半人马。此乃某生平最大之败也。',
          '官渡之战': '官渡之战，某以少胜多，奇袭乌巢，烧毁袁绍粮草，最终击败袁绍，统一北方。此乃某生平最得意之战也。',
          '许褚': '许褚字仲康，某之猛将也。容貌雄毅，勇力绝人，号"虎痴"。曾裸衣斗马超，多次救某于危难之中。',
          '典韦': '典韦，某之爱将也。形貌魁梧，膂力过人，号"古之恶来"。为保护某而战死，某甚为痛惜。'
        },
        sunQuan: {
          '长坂坡': '长坂坡之战，刘备被曹军追击，大败而逃。后派诸葛亮来江东求救，某与刘备联手抗曹。',
          '赤壁之战': '赤壁之战，某与刘备联手，以周瑜为大都督，火烧曹军，大破曹操八十万大军。此乃江东存亡之战也。',
          '周瑜': '周瑜字公瑾，某之大都督也。姿质风流，仪容秀丽，精音律，有"曲有误，周郎顾"之誉。赤壁之战中立下大功。',
          '吕蒙': '吕蒙字子明，某之大将也。由武夫变为儒将，"士别三日，当刮目相待"说的正是他。袭取荆州，擒杀关羽，立下大功。',
          '陆逊': '陆逊字伯言，某之大将也。夷陵之战中火烧连营，大败刘备。后任丞相，为吴国鞠躬尽瘁。'
        }
      };

      // 检查当前角色是否有特定关键词响应
      const characterResponses = characterSpecificResponses[currentCharacterKey];
      if (characterResponses) {
        for (const [keyword, keywordResponse] of Object.entries(characterResponses)) {
          if (questionLower.includes(keyword)) {
            response = keywordResponse;
            break;
          }
        }
      }
    }

    // 如果提到了人物，优先回复关于人物的内容
    if (!response && mentionedCharacters.length > 0) {
      // 优先选择第一个提到的人物
      const mentionedChar = mentionedCharacters[0];

      // 检查是否询问的是当前角色与被提及角色的关系
      for (const [relationType, keywords] of Object.entries(relationshipKeywords)) {
        if (keywords.some(keyword => questionLower.includes(keyword))) {
          const currentCharName = characterDetails[currentCharacterKey].name;

          // 生成关系回复
          switch (relationType) {
            case 'friend':
              response = `${responseTypes.personal[Math.floor(Math.random() * responseTypes.personal.length)]}${mentionedChar.name}与${currentCharName}乃是莫逆之交，相交甚深。`;
              break;
            case 'enemy':
              response = `${responseTypes.historical[Math.floor(Math.random() * responseTypes.historical.length)]}${mentionedChar.name}与${currentCharName}曾多次交锋，互为劲敌。`;
              break;
            case 'subordinate':
              response = `${responseTypes.introduction[Math.floor(Math.random() * responseTypes.introduction.length)]}${mentionedChar.name}乃是${currentCharName}麾下得力干将，忠心耿耿，屡立战功。`;
              break;
            case 'superior':
              response = `${responseTypes.personal[Math.floor(Math.random() * responseTypes.personal.length)]}${mentionedChar.name}对${currentCharName}有知遇之恩，某对其感恩戴德。`;
              break;
            case 'family':
              response = `${responseTypes.narrative[Math.floor(Math.random() * responseTypes.narrative.length)]}${mentionedChar.name}与${currentCharName}乃结义兄弟，情同手足。`;
              break;
            case 'colleague':
              response = `${responseTypes.introduction[Math.floor(Math.random() * responseTypes.introduction.length)]}${mentionedChar.name}与${currentCharName}曾一同共事，互相敬重。`;
              break;
            default:
              response = generateCharacterResponse(mentionedChar.key, mentionedChar.detail, questionType, userMessage);
          }

          // 如果已经生成了关系回复，则跳出循环
          if (response) {
            break;
          }
        }
      }

      // 如果没有生成关系回复，则生成关于人物的一般回复
      if (!response) {
        response = generateCharacterResponse(mentionedChar.key, mentionedChar.detail, questionType, userMessage);
      }
    }
    // 如果提到了历史事件，回复关于事件的内容
    else if (!response && mentionedEvents.length > 0) {
      const mentionedEvent = mentionedEvents[0];
      response = generateEventResponse(mentionedEvent);
    }
    // 否则生成基于当前角色的通用回复
    else if (!response) {
      response = generateGeneralResponse(currentCharacterKey);
    }

    // 根据人物性格调整回复结尾
    const endings = {
      liuBei: '，不知先生以为如何？',
      caoCao: '，此乃孤之肺腑之言也！',
      sunQuan: '，还请将军指教。'
    };

    // 随机添加结尾（30%的概率）
    if (Math.random() < 0.3 && endings[currentCharacterKey]) {
      response += endings[currentCharacterKey];
    }

    return response;
  } catch (error) {
    console.error('生成关键词匹配回复时出错:', error);

    // 返回一个更符合人物性格的默认回复
    const defaultResponses = {
      liuBei: '备当以仁义为本，以礼待人，愿闻先生高见。',
      caoCao: '夫英雄者，胸怀大志，腹有良谋，将军可有此等抱负？',
      sunQuan: '能用众力，则无敌于天下矣，孤当与江东父老共图大事。'
    };

    return defaultResponses[currentCharacterKey] || '某以为此事尚需从长计议，将军以为如何？';
  }
}

// 主要的回复生成函数
export async function generateResponse(character, userMessage) {
  try {
    console.log(`使用关键词匹配系统生成${character}的回复`);

    // 生成基于关键词的回复
    const aiResponse = generateKeywordBasedResponse(character, userMessage);

    // 模拟API延迟，让用户体验更自然
    await new Promise(resolve => setTimeout(resolve, 800));

    return aiResponse;
  } catch (error) {
    console.error('生成回复时出错:', error);

    // 返回默认回复
    return generateKeywordBasedResponse(character, userMessage);
  }
}

// 为了兼容性，尝试导入原始模块
let router = null;
try {
  const express = await import('express');
  router = express.Router();

  // POST endpoint for chat messages
  router.post('/message', async (req, res) => {
    try {
      const { character, userMessage } = req.body;

      if (!character || !userMessage) {
        return res.status(400).json({
          success: false,
          error: 'Character and message are required'
        });
      }

      // Generate AI response using keyword matching
      const aiResponse = await generateResponse(character, userMessage);

      res.json({
        success: true,
        response: aiResponse
      });
    } catch (error) {
      console.error('Error handling chat message:', error);
      res.status(500).json({
        success: false,
        error: 'Internal server error',
        details: error.message
      });
    }
  });

} catch (error) {
  // 如果导入失败，仍然可以正常工作，因为主函数已经导出
  console.log('注意：express模块导入失败，但回复生成功能仍然可用');
}

// 导出路由器供外部使用
export default router;